<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>

        /**
         * 1. num >>> string
         * 2. string >>> arr
         * 3. arr >>> arr.reverse()
         * 4. newArr >>> newStr
         * 5. newStr >>> newNum
         */
        function reverseInt1 (num) {
            // 判断正数
            let isPos = num >= 0;
            if (!isPos) {
                num = -num;
            }
            // const str = String(num);
            // const arr = str.split('');
            // const newArr = arr.reverse();
            // const newStr = newArr.join('');
            // let result = Number(newStr); // 0007
            result = Number(
                num
                .toString()
                .split('')
                .reverse()
                .join('')
            );

            const max = 2 ** 31 - 1;
            const min = -(2 ** 31);
            result = isPos ? result : -result;
            if (result > max || result < min) {
                return 0;
            }
            return result;
        }

        // console.log(reverseInt(1234)); // 4321

        /**
         * 纯数学方式
         * 1234
         * 1. 1234 >>> 4, 123
         * 2. 123 >>> 3, 12
         * 3. 12 >>> 2, 1
         * 4. 1 >>> 1, 1 (退出)(条件为num > 0)
         * 5. 1 >>> 1, 1
         * 
         * 7000
         */ 
        function reverseInt2 (num) {
            let result = 0; // 4
            while (num !== 0) {
                const unit = num % 10; // 0
                num = (num - unit) / 10; // 700
                result = result * 10 + unit;
            }
            const max = 2 ** 31 - 1;
            const min = -(2 ** 31);
            if (result > max || result < min) {
                return 0;
            }
            return result;
        }

        function performance (name, cb, count = 100000) {
            console.time(name);
            for (let i = 0; i < count; i++) {
                cb();
            }
            console.timeEnd(name);
        }

        // 测试性能
        // performance('字符串方法', function () {
        //     reverseInt1(247139218);
        // }, 500000);

        // performance('数学方法', function () {
        //     reverseInt2(247139218);
        // }, 500000);

        // 三种转换数字类型的性能
        performance('Number', function () {
            Number('1231231231');
        }, 500000);

        performance('parseInt', function () {
            parseInt('1231231231');
        }, 500000);

        performance('-0', function () {
            '1231231231' - 0;
        }, 500000);

    </script>
</body>
</html>